﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace KanbanApi.Component
{
    public class CustomMessageHandler : DelegatingHandler
    {
        static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            //return base.SendAsync(request, cancellationToken);
            //记录请求内容
            if (request.Content != null)
            {
                string msg = $"Request | Request Method: {request.Method},Request Uri: {request.RequestUri.AbsoluteUri}, Request Content: { request.Content.ReadAsStringAsync().Result}";
                loginfo.Info(msg);
            }
            //发送HTTP请求到内部处理程序，在异步处理完成后记录相应内容
            return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((task) =>
            {
                string result = task.Result.Content == null ? "Bad Request" : task.Result.Content.ReadAsStringAsync().Result;
                string msg = $"Response | Request Method:{request.Method},Request Uri: {request.RequestUri.AbsoluteUri}, Response Content: {result}";

                // 记录响应内容
                loginfo.Info(msg);
                return task.Result;
            });
        }
    }
}